<?php

namespace App\Api\Http\Middleware;

use Closure;

class SetCorsHeaders
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure                 $next
     *
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        /** @var \Symfony\Component\HttpFoundation\Response $response */
        $response = $next($request);

        //非生产环境直接返回
        if (app()->environment('production')) {
            return $response;
        }

        $headers = $response->headers;
        $origin = $request->header('Origin');
        if ($origin) {
            $headers->set('Access-Control-Allow-Origin', $origin);
            $allow_headers = [
                'token',
                'X-Requested-With',
                'Client-Options',
                'Content-Type',
                'Access-Control-Request-Headers',
                'Access-Control-Allow-Origin',
            ];
            $headers->set('Access-Control-Allow-Headers', implode(',', $allow_headers));
            $headers->set('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS');
            $headers->set('Access-Control-Allow-Credentials', 'true');
        }

        return $response;
    }
}
